#include "U2Framework.h"

#include "U2LogManager.h"
#include "U2Log.h"
#include "U2ConfigFile.h"
#include "U2Timer.h"
#include "U2SceneManager.h"
#include "U2RenderWindow.h"
#include "U2Camera.h"
#include "U2Viewport.h"
#include "U2Timer.h"
#include "U2Camera.h"

#if U2_PLATFORM == U2_PLATFORM_APPLE || U2_PLATFORM == U2_PLATFORM_APPLE_IOS
#include "macUtils.h"
#endif


U2EG_NAMESPACE_USING


template<> U2Framework* U2Singleton<U2Framework>::s_pSingleton = 0;


U2Framework::U2Framework()
{
	m_bShutDownOgre     = false;
	m_iNumScreenShots   = 0;
    
	m_pRoot				= 0;
	m_pSceneMgr			= 0;
	m_pRenderWnd        = 0;
	m_pCamera			= 0;
	m_pViewport			= 0;
	m_pLog				= 0;
	m_pTimer			= 0;
    
//	m_pInputMgr			= 0;
//	m_pKeyboard			= 0;
//	m_pMouse			= 0;
    
#if U2_PLATFORM == U2_PLATFORM_APPLE
    m_ResourcePath = macBundlePath() + "/Contents/Resources/";
#elif defined(U2_IS_IOS)
    m_ResourcePath = macBundlePath() + "/";
#else
    m_ResourcePath = "";
#endif
    
    m_FrameEvent        = FrameEvent();
}

//|||||||||||||||||||||||||||||||||||||||||||||||
#if defined(U2_IS_IOS)
bool U2Framework::initOgre(U2String wndTitle/*, OIS::KeyListener *pKeyListener, OIS::MultiTouchListener *pMouseListener*/)
#else
bool U2Framework::initOgre(U2String wndTitle/*, OIS::KeyListener *pKeyListener, OIS::MouseListener *pMouseListener*/)
#endif
{
    new U2LogManager();

	m_pLog = U2LogManager::getSingleton().createLog("U2Logfile.log", true, true, false);
	m_pLog->setDebugOutputEnabled(true);
    
    U2String pluginsPath;
    // only use plugins.cfg if not static
#ifndef U2_STATIC_LIB
    pluginsPath = m_ResourcePath + "plugins.cfg";
#endif
    
    m_pRoot = new U2Root(pluginsPath, macBundlePath() + "/u2.cfg");
    
#ifdef U2_STATIC_LIB
    m_StaticPluginLoader.load();
#endif
    
    /**********************@@@@@@@@@@@@@@@@@@@@@
	if(!m_pRoot->showConfigDialog())
		return false;
     */
    m_pRoot->restoreConfig();
    
	m_pRenderWnd = m_pRoot->initialise(true, wndTitle);
    
//	m_pSceneMgr = m_pRoot->createSceneManager(ST_GENERIC, "SceneManager");
//	
//	m_pCamera = m_pSceneMgr->createCamera("Camera");
//    m_pCamera->setPosition(U2Vector3(0, 0, 20));
//    /**********************@@@@@@@@@@@@@@@@@@@@@
//	m_pCamera->setPosition(U2Vector3(0, 60, 60));
//	m_pCamera->lookAt(U2Vector3(0, 0, 0));
//	m_pCamera->setNearClipDistance(1);
//     */
//    
//	m_pViewport = m_pRenderWnd->addViewport(m_pCamera);
//	m_pViewport->setBackgroundColour(U2ColourValue(0.8f, 0.7f, 0.6f, 1.0f));
//	m_pCamera->setAspectRatio(u2real(m_pViewport->getActualWidth()) / u2real(m_pViewport->getActualHeight()));
//	m_pViewport->setCamera(m_pCamera);
    
	unsigned long hWnd = 0;
    m_pRenderWnd->getCustomAttribute("WINDOW", &hWnd);
    
    /**********************@@@@@@@@@@@@@@@@@@@@@
    OIS::ParamList paramList;
	paramList.insert(OIS::ParamList::value_type("WINDOW", U2StringConverter::toString(hWnd)));
    
	m_pInputMgr = OIS::InputManager::createInputSystem(paramList);
    
#if !defined(U2_IS_IOS)
    m_pKeyboard = static_cast<OIS::Keyboard*>(m_pInputMgr->createInputObject(OIS::OISKeyboard, true));
	m_pMouse = static_cast<OIS::Mouse*>(m_pInputMgr->createInputObject(OIS::OISMouse, true));
    
	m_pMouse->getMouseState().height = m_pRenderWnd->getHeight();
	m_pMouse->getMouseState().width	 = m_pRenderWnd->getWidth();
#else
	m_pMouse = static_cast<OIS::MultiTouch*>(m_pInputMgr->createInputObject(OIS::OISMultiTouch, true));
#endif
    
#if !defined(U2_IS_IOS)
	if(pKeyListener == 0)
		m_pKeyboard->setEventCallback(this);
	else
		m_pKeyboard->setEventCallback(pKeyListener);
#endif
    
	if(pMouseListener == 0)
		m_pMouse->setEventCallback(this);
	else
		m_pMouse->setEventCallback(pMouseListener);
    */
    
	U2String secName, typeName, archName;
	U2ConfigFile cf;
    cf.load(m_ResourcePath + "resources.cfg");
    
	U2ConfigFile::SectionIterator seci = cf.getSectionIterator();
    while (seci.hasMoreElements())
    {
        secName = seci.peekNextKey();
		U2ConfigFile::SettingsMultiMap *settings = seci.getNext();
        U2ConfigFile::SettingsMultiMap::iterator i;
        for (i = settings->begin(); i != settings->end(); ++i)
        {
            typeName = i->first;
            archName = i->second;
#if U2_PLATFORM == U2_PLATFORM_APPLE || defined(U2_IS_IOS)
            // OS X does not set the working directory relative to the app,
            // In order to make things portable on OS X we need to provide
            // the loading with it's own bundle path location
            if (!U2StringUtil::startsWith(archName, "/", false)) // only adjust relative dirs
                archName = U2String(m_ResourcePath + archName);
#endif
            U2ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
        }
    }
	U2TextureManager::getSingleton().setDefaultNumMipmaps(0);
	U2ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
    
    
    // ******************** begin,  这部分的顺序与资源加载互换了下，待完善后请与Ogre原版对比，恢复顺序
    m_pSceneMgr = m_pRoot->createSceneManager(ST_GENERIC, "SceneManager");
	
	m_pCamera = m_pSceneMgr->createCamera("Camera");
    m_pCamera->setPosition(U2Vector3(0, 0, 20));
    /**********************@@@@@@@@@@@@@@@@@@@@@
     m_pCamera->setPosition(U2Vector3(0, 60, 60));
     m_pCamera->lookAt(U2Vector3(0, 0, 0));
     m_pCamera->setNearClipDistance(1);
     */
    
	m_pViewport = m_pRenderWnd->addViewport(m_pCamera);
	m_pViewport->setBackgroundColour(U2ColourValue(0.8f, 0.7f, 0.6f, 0.5f));
	m_pCamera->setAspectRatio(u2real(m_pViewport->getActualWidth()) / u2real(m_pViewport->getActualHeight()));
	m_pViewport->setCamera(m_pCamera);
    // ******************** end
    
	m_pTimer = U2_NEW U2Timer();
	m_pTimer->reset();
    
	m_pRenderWnd->setActive(true);
    
	return true;
}

U2Framework::~U2Framework()
{
    /**********************@@@@@@@@@@@@@@@@@@@@@
    if(m_pInputMgr) OIS::InputManager::destroyInputSystem(m_pInputMgr);
     */
    
#ifdef U2_STATIC_LIB
    m_StaticPluginLoader.unload();
#endif
    if(m_pRoot)     delete m_pRoot;
}

/**********************@@@@@@@@@@@@@@@@@@@@@
bool U2Framework::keyPressed(const OIS::KeyEvent &keyEventRef)
{
	return true;
}

bool U2Framework::keyReleased(const OIS::KeyEvent &keyEventRef)
{
	return true;
}

//|||||||||||||||||||||||||||||||||||||||||||||||

#if defined(U2_IS_IOS)
bool U2Framework::touchMoved(const OIS::MultiTouchEvent &evt)
{
	return true;
}

//|||||||||||||||||||||||||||||||||||||||||||||||

bool U2Framework::touchPressed(const OIS:: MultiTouchEvent &evt)
{
#pragma unused(evt)
	return true;
}

//|||||||||||||||||||||||||||||||||||||||||||||||

bool U2Framework::touchReleased(const OIS:: MultiTouchEvent &evt)
{
#pragma unused(evt)
	return true;
}

bool U2Framework::touchCancelled(const OIS:: MultiTouchEvent &evt)
{
#pragma unused(evt)
	return true;
}

#else

bool U2Framework::mouseMoved(const OIS::MouseEvent &evt)
{
	return true;
}

bool U2Framework::mousePressed(const OIS::MouseEvent &evt, OIS::MouseButtonID id)
{
	return true;
}

bool U2Framework::mouseReleased(const OIS::MouseEvent &evt, OIS::MouseButtonID id)
{
	return true;
}
#endif
 
 */

void U2Framework::updateOgre(double timeSinceLastFrame)
{
	m_FrameEvent.timeSinceLastFrame = timeSinceLastFrame;
}
